package com.study.system.user.config;

import com.study.system.entity.User;
import com.study.system.util.JwtUtils;
import com.study.system.util.RsaUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;
import java.util.List;

/**
 * 令牌验证过滤器
 */
@Component
public class TokenValidateFilter extends GenericFilterBean {

    private Logger logger = LoggerFactory.getLogger(TokenValidateFilter.class);

    //过滤
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获得请求头中的token
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("Authorization");
        if(token == null){
            logger.error("令牌为空");
        }else{
            try {
                //解析令牌
                User user = JwtUtils.getUserFromToken(token, RsaUtils.publicKey);
                logger.info("令牌解析成功:{}", user.getUsername());
                //创建新令牌
                UsernamePasswordAuthenticationToken token1 =
                        new UsernamePasswordAuthenticationToken(user.getUsername(),"",
                                AuthorityUtils.commaSeparatedStringToAuthorityList(""));
                //将新令牌交给security
                SecurityContextHolder.getContext().setAuthentication(token1);
            }catch (Exception ex){
                logger.error("令牌解析失败");
            }
        }
        //放行请求到下一个过滤器
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
